import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { saveAs } from 'file-saver';
import { HTTP_STATIC_TEST } from '../common/configuration';
import { map } from "rxjs/operators";
import { Subject } from 'rxjs';

@Injectable()
export class ReportService {
    private routeMsgPushSource = new Subject<any>();
    routeMsgPush$ = this.routeMsgPushSource.asObservable();
    constructor(private http: HttpClient) { }

    /** 加载报表信息 */
    loadReport(id: number) {
        return this.http.get('/report/api/statis/load?id=' + id).pipe(
            map((res: Response) => res['data'])
        )
    }

    /**获取当前用户可查看的报表列表 */
    listReports() {
        return this.http.get('/report/api/statis/list').pipe(
            map((res: Response) => res['data'])
        )
    }

    /**加载查询条件 */
    loadConditionFields(reportId: number) {
        return this.http.get('/report/api/statis/conds?id=' + reportId).pipe(
            map((res: Response) => res['data'])
        )
    }
    /** 加载查询统计表头 */
    loadStatisHeaderColumns(reportId: number, detailFlag = 0) {
        return this.http.get('/report/api/statis/header?id=' + reportId + '&detailFlag=' + detailFlag).pipe(
            map((res: Response) => res['data'])
        )
    }
    /**加载统计数据 */
    loadStatisRecords(conds: any, reportId, pageSize = 30, pageNum = 1, detailFlag = 0) {
        return this.http.post('/report/api/statis/execute?id=' + reportId + '&pageSize=' + pageSize + '&pageNum=' + pageNum + '&detailFlag=' + detailFlag, conds).pipe(
            map((res: Response) => res['data'])
        )
    }

    /** 获取数据源列表 */
    listDataSource() {
        return this.http.get('/report/api/datasource/list').pipe(
            map((res: Response) => res['data'])
        )
    }
    /** 获取数据视图树 */
    listDataviewTree() {
        return this.http.get('/report/api/dataview/list').pipe(
            map((res: Response) => res['data'])
        )
    }
    /** 获取数据视图详情 */
    loadDataviewDetail(id: number) {
        return this.http.get('/report/api/dataview/detail?id=' + id).pipe(
            map((res: Response) => res['data'])
        )
    }
    /** 加载数据源对应的数据库表 */
    listTableViews(dsName: string) {
        return this.http.get('/report/api/dataview/listtableviews?dsName=' + dsName).pipe(
            map((res: Response) => res['data'])
        )
    }
    /** 文件下载 */
    downloadReport(reportId: number, conds: any[], fileName: string, detailFlag = 0) {
        return this.http.post('/report/api/statis/download?id=' + reportId, conds, { 'responseType': 'blob' }).pipe(
            map(res => saveAs(res, fileName))
        );
    }

    /** 统计查询通讯 */
    announceMission(data: any) {
        this.routeMsgPushSource.next(data);
    }
}